using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Collections.Generic;

namespace FreeFlow.Administration
{
  /// <summary>
  /// The types of designer log entries that can be shown
  /// </summary>
  [Flags]
  public enum DesignerLogSources
  {
    /// <summary>User authentication failures.</summary>
    AuthenticationFailure = 0x01,
    /// <summary>New version of a procedure published.</summary>
    DesignerPublishing = 0x02,
    /// <summary>Engine errors and any other entries.</summary>
    EngineError = 0x04,
    /// <summary>Return all entries</summary>
    All = 0x07
  }

	/// <summary>
	/// A collection of designer log entries.
	/// </summary>
	public sealed class DesignerLog : DatabaseAware, IRefreshable, IClearable, IList, IBindingList, IEnumerable<DesignerLogEntry>
	{
    private List<DesignerLogEntry> logEntries;
    private string mapName;
    private string procedureName;
    private string folderId;
    private string userName;
    private DesignerLogSources sources;
    /// <summary>
    /// Initializes a new instance of the <see cref="DesignerLog"/> class for all entries in the database.
    /// </summary>
    /// <param name="server">The server.</param>
    public DesignerLog(Server server) : this(server, DesignerLogSources.All)
    {
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="DesignerLog"/> class for the specified log sources.
    /// </summary>
    /// <param name="server">The database server.</param>
    /// <param name="sources">The type of log entries to retrieve.</param>
    public DesignerLog(Server server, DesignerLogSources sources) : base(server)
    {
      this.sources = sources;
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="DesignerLog"/> class for the specified map.
    /// </summary>
    /// <param name="server">The server.</param>
    /// <param name="map">The map.</param>
    public DesignerLog(Server server, Map map) : this(server)
    {
      if (map != null)
        mapName = map.Name;
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="DesignerLog"/> class for the specified procedure.
    /// </summary>
    /// <param name="server">The server.</param>
    /// <param name="procedure">The procedure.</param>
    public DesignerLog(Server server, Procedure procedure) : this(server)
    {
      if (procedure != null)
        procedureName = procedure.Name;
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="DesignerLog"/> class for the specified folder.
    /// </summary>
    /// <param name="server">The server.</param>
    /// <param name="folderId">The folder id.</param>
    public DesignerLog(Server server, string folderId) : this(server)
    {
      this.folderId = folderId;
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="DesignerLog"/> class for the specified user.
    /// </summary>
    /// <param name="server">The server.</param>
    /// <param name="user">The user.</param>
    public DesignerLog(Server server, User user) : this(server)
    {
      this.userName = user.Name;
    }

    private string GetWhereClause()
    {
      string whereClause = "WHERE 1=1";

      if (mapName != null)
        whereClause = string.Format("WHERE eMapName = '{0}'", SqlEscape(mapName));
      else if (procedureName != null)
        whereClause = string.Format("WHERE eProcedureName = '{0}'", SqlEscape(procedureName));
      else if (folderId != null)
        whereClause = string.Format("WHERE eFolderID = '{0}'", folderId);
      else if (userName != null)
        whereClause = string.Format("WHERE eUserName = '{0}'", userName);

      // source of the log
      if (sources != DesignerLogSources.All) 
      {
        whereClause = whereClause + " AND (";
        if ((sources & DesignerLogSources.AuthenticationFailure) == DesignerLogSources.AuthenticationFailure)
          whereClause = whereClause + "eComponentType = 'Authentication'";
        else
          whereClause = whereClause + "1=0";
        
        if ((sources & DesignerLogSources.DesignerPublishing) == DesignerLogSources.DesignerPublishing) 
          whereClause = whereClause + " OR eComponentType = 'Designer'";
        else
          whereClause = whereClause + " OR 1=0";
        
        if ((sources & DesignerLogSources.EngineError) == DesignerLogSources.EngineError) 
          whereClause = whereClause + " OR (eComponentType <> 'Authentication' AND eComponentType <> 'Designer'))";
        else
          whereClause = whereClause + " OR 1=0)";
      }

      return whereClause;
    }

    private void GetLogEntries()
    {
      if (logEntries == null)
      {
        logEntries = new List<DesignerLogEntry>();
        
        string sql = string.Format(
          "SELECT * FROM eLog {0} ORDER BY eLogID DESC", GetWhereClause());
        using (IDataReader reader = Server.ExecuteReader(sql))
        {
          while (reader.Read()) 
          {
            DesignerLogEntry entry = new DesignerLogEntry(Server, reader);
            logEntries.Add(entry);
          }
        }
      }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
      GetLogEntries();
      return logEntries.GetEnumerator();
    }

    #region IEnumerable<DesignerLogEntry> Members

    /// <summary>
    /// Returns an enumerator that iterates through the collection.
    /// </summary>
    /// <returns>
    /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
    /// </returns>
    public IEnumerator<DesignerLogEntry> GetEnumerator()
    {
      GetLogEntries();
      return logEntries.GetEnumerator();
    }

    #endregion

    /// <summary>
    /// Gets the number of entries in this designer log collection.
    /// </summary>
    public int Count
    {
      get
      {
        GetLogEntries();
        return logEntries.Count;
      }
    }

    /// <summary>
    /// Gets the <see cref="DesignerLogEntry"/> at the specified index.
    /// </summary>
    public DesignerLogEntry this[int index]
    {
      get
      {
        GetLogEntries();
        return (DesignerLogEntry)logEntries[index];
      }
    }

    /// <summary>
    /// Refreshes this instance.
    /// </summary>
    public void Refresh()
    {
      logEntries = null;
    }

    /// <summary>
    /// Deletes entries older than the specified number of days.
    /// </summary>
    /// <param name="days">The number of days.</param>
    /// <returns>The number of entries deleted.</returns>
    public int DeleteEntriesOlderThan(int days)
    {
      int deleted = Server.ExecuteNonQuery(
        string.Format("DELETE FROM eLog {0} AND eTime < " + Server.GetDate + "-{1}", GetWhereClause(), days));
      Refresh();
      return deleted;
    }

    #region IClearable Members

    /// <summary>
    /// Clears these designer log entries from the database.
    /// </summary>
    public void Clear()
    {
      Server.ExecuteNonQuery(string.Format("DELETE FROM eLog {0}", GetWhereClause()));
      Refresh();
    }

    #endregion
    #region IList Members

    /// <summary>
    /// Gets a value indicating whether the <see cref="T:System.Collections.IList"/> is read-only.
    /// </summary>
    public bool IsReadOnly
    {
      get
      {
        return true;
      }
    }

    object IList.this[int index]
    {
      get
      {
        GetLogEntries();
        if ((index >= 0) && (index < Count))
          return logEntries[index];
        return null;
      }
      set
      {
        throw new NotSupportedException(readOnlyListMessage);
      }
    }

    /// <summary>
    /// Removes the <see cref="T:System.Collections.IList"/>
    /// item at the specified index.
    /// </summary>
    /// <param name="index">The zero-based index of the item to remove.</param>
    /// <exception cref="T:System.ArgumentOutOfRangeException">
    /// 	<paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.IList"/>.</exception>
    /// <exception cref="T:System.NotSupportedException">
    /// 	<para>The <see cref="T:System.Collections.IList"/> is read-only.</para>
    /// 	<para>-or-</para>
    /// 	<para>The <see cref="T:System.Collections.IList"/> has a fixed size.</para>
    /// </exception>
    public void RemoveAt(int index)
    {
      GetLogEntries();
      DesignerLogEntry entry = logEntries[index];
      Remove(entry);
    }

    void IList.Insert(int index, object value)
    {
      throw new NotSupportedException(readOnlyListMessage);
    }

    void IList.Remove(object value)
    {
      Remove((DesignerLogEntry)value);
    }

    /// <summary>
    /// Removes the specified log entry.
    /// </summary>
    /// <param name="entry">The entry to remove</param>
    public void Remove(DesignerLogEntry entry)
    {
      GetLogEntries();
      if (logEntries.Contains(entry))
      {
        entry.Delete();
        logEntries.Remove(entry);
      }
    }

    /// <summary>
    /// Determines whether the <see cref="T:System.Collections.IList"/> contains a specific value.
    /// </summary>
    /// <param name="value">The <see cref="T:System.Object"/> to locate in the <see cref="T:System.Collections.IList"/>.</param>
    /// <returns>
    /// 	<see langword="true"/> if the <see cref="T:System.Object"/>
    /// is found in the <see cref="T:System.Collections.IList"/>; otherwise, <see langword="false"/>.
    /// </returns>
    public bool Contains(object value)
    {
      GetLogEntries();
      return logEntries.Contains((DesignerLogEntry)value);
    }

    /// <summary>
    /// Determines the index of a
    /// specific item in the <see cref="T:System.Collections.IList"/>.
    /// </summary>
    /// <param name="value">The <see cref="T:System.Object"/> to locate in the <see cref="T:System.Collections.IList"/>.</param>
    /// <returns>
    /// The index of <paramref name="value"/> if found in the list; otherwise, -1.
    /// </returns>
    public int IndexOf(object value)
    {
      GetLogEntries();
      return logEntries.IndexOf((DesignerLogEntry)value);
    }

    int IList.Add(object value)
    {
      throw new NotSupportedException(readOnlyListMessage);
    }

    /// <summary>
    /// Gets a value indicating whether the <see cref="T:System.Collections.IList"/> has a fixed size.
    /// </summary>
    public bool IsFixedSize
    {
      get
      {
        return true;
      }
    }

    #endregion
    #region ICollection Members

    /// <summary>
    /// Gets a value
    /// indicating whether access to the <see cref="T:System.Collections.ICollection"/> is synchronized
    /// (thread-safe).
    /// </summary>
    public bool IsSynchronized
    {
      get
      {
        return false;
      }
    }

    /// <summary>
    /// Copies the elements of
    /// the <see cref="T:System.Collections.ICollection"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
    /// </summary>
    /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param>
    /// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
    /// <exception cref="T:System.ArgumentNullException">
    /// 	<paramref name="array"/> is <see langword="null"/>.</exception>
    /// <exception cref="T:System.ArgumentOutOfRangeException">
    /// 	<paramref name="index"/> is less than zero.</exception>
    /// <exception cref="T:System.ArgumentException">
    /// 	<para>
    /// 		<paramref name="array"/> is multidimensional.</para>
    /// 	<para>-or-</para>
    /// 	<para>
    /// 		<paramref name="index"/> is equal to or greater than the length of <paramref name="array"/>.</para>
    /// 	<para>-or-</para>
    /// 	<para>The number of elements in the source <see cref="T:System.Collections.ICollection"/> is greater than the available space from <paramref name="index"/> to the end of the destination <paramref name="array"/>.</para>
    /// </exception>
    /// <exception cref="T:System.InvalidCastException">The type of the source <see cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the destination <paramref name="array"/>.</exception>
    public void CopyTo(DesignerLogEntry[] array, int index)
    {
      GetLogEntries();
      logEntries.CopyTo(array, index);
    }

    void ICollection.CopyTo(Array array, int index)
    {
      CopyTo((DesignerLogEntry[])array, index);
    }

    /// <summary>
    /// Gets an object that
    /// can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>.
    /// </summary>
    public object SyncRoot
    {
      get
      {
        return null;
      }
    }

    #endregion
    #region IBindingList Members

    void IBindingList.ApplySort(PropertyDescriptor property, ListSortDirection direction)
    {
      GetLogEntries();
      sortProperty = property;
      sortDirection = direction;
      logEntries.Sort(new Comparer<DesignerLogEntry>(sortProperty, sortDirection));
    }

    private PropertyDescriptor sortProperty;
    PropertyDescriptor IBindingList.SortProperty
    {
      get
      {
        return sortProperty;
      }
    }

    bool IBindingList.SupportsSorting
    {
      get
      {
        return true;
      }
    }

    bool IBindingList.IsSorted
    {
      get
      {
        return (sortProperty != null);
      }
    }

    void IBindingList.RemoveSort()
    {
      sortProperty = null;
    }

    private ListSortDirection sortDirection;
    ListSortDirection IBindingList.SortDirection
    {
      get
      {
        return sortDirection;
      }
    }

    #region not implemented 
    int IBindingList.Find(PropertyDescriptor property, object key)
    {
      return 0;
    }

    bool IBindingList.AllowRemove
    {
      get
      {
        return false;
      }
    }

    bool IBindingList.SupportsSearching
    {
      get
      {
        return false;
      }
    }

    private ListChangedEventHandler listChanged;
    event ListChangedEventHandler IBindingList.ListChanged
    {
      add { listChanged += value; }
      remove { listChanged -= value; }

    }

    bool IBindingList.SupportsChangeNotification
    {
      get
      {
        return false;
      }
    }

    object IBindingList.AddNew()
    {
      return null;
    }

    bool IBindingList.AllowEdit
    {
      get
      {
        return false;
      }
    }

    void IBindingList.RemoveIndex(PropertyDescriptor property)
    {
    }

    void IBindingList.AddIndex(PropertyDescriptor property)
    {
    }

    bool IBindingList.AllowNew
    {
      get
      {
        return false;
      }
    }

    #endregion
    #endregion
  }
}
